package com.example.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;


/**
 * @ClassName MongoDbService
 * @Desecription TODO 1.2新增
 * @Author gjy
 * @Date 2021/3/31 16:15
 * @Version 1.2
 **/
@Service
public class MongoDbService {

    private static final Logger logger = LoggerFactory.getLogger(MongoDbService.class);

    @Autowired
    private MongoTemplate mongoTemplate;


    public String saveObj() {
        User user = new User();
        user.setName("张三");
        user.setSex("男");
        mongoTemplate.save(user);
        return "添加成功";
    }

    public String insert(){
        User user = new User();
        user.setName("张三");
        user.setSex("男");
        mongoTemplate.insert(user);
        return "添加成功";
    }

    public String insertMap(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("sex","男");
        //使用map传入数据必须指定集合
        mongoTemplate.insert(map,"test");
        return "添加map成功";
    }

    public String inserJSON(){
        JSONObject json = new JSONObject();
        json.put("name","json");
        json.put("value","测试存放json");
        mongoTemplate.insert(json,"test");
        return "添加json成功";
    }

    public User findByName(String name){
        Query query = new Query(Criteria.where("name").is(name));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }

    public User findOne(String name,String sex){
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("name").is(name),Criteria.where("sex").is("女"));
        Query query = new Query(criteria);
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }

}
